import { expect } from '@jest/globals';
import path from 'path';

import { runHvigorAsync } from '../../common/common';
import { commonFileOperation, initPreviewConfigFile } from '../../plugins/common-fun';
import {
  AbilityType,
  APIType,
  APIVersion,
  CaseLevel,
  LanguageType,
  ModuleTemplateType,
  RuntimeOSType,
  SDKType
} from '../../plugins/project-builder/models/constants';
import { TestCaseBuilder } from '../../plugins/task-builder/task-case-builder';
import { ProjectBuildOption, TestCaseFun } from '../../plugins/task-builder/test-case';
import { TestTaskOptionBuilder } from '../../plugins/task-builder/test-task-option';

const projectBuilderOption: ProjectBuildOption = {
  template: {
    sdk: SDKType.Single,
    runtimeOS: RuntimeOSType.HarmonyOS,
    apiVersion: APIVersion.API10,
    apiType: APIType.STAGE,
    language: LanguageType.ArkTs,
    abilityType: AbilityType.Application,
    entryTemplateType: ModuleTemplateType.EmptyAbility
  }
};

/**
 * 1、新建工程
 * 2、预览
 * 3、在页面最后添加#符号
 * 4、删除该符号
 * 预期结果：
 * 删除该符号后触发热加载生效
 * 实际结果：
 * 符合预期结果
 *
 * @param {Project} project
 * @param {TestTaskOption} taskConfig
 * @param {ICaseRecord} record
 * @return res
 */
const testfun: TestCaseFun = async (project, taskConfig, record) => {
  // 1. 首先正常执行预览，成功
  const entryRootPath = project.getModule('entry').moduleRootPath();
  await initPreviewConfigFile(entryRootPath);
  // eslint-disable-next-line max-len
  const commands: string[] = '--mode module -p module=entry@default -p product=default -p pageType=page -p compileResInc=true -p previewMode=true -p buildRoot=.preview PreviewBuild --watch --parallel --daemon'.split(' ');
  const result = await runHvigorAsync(project.projectRootPath(), commands);
  record.addStep('执行预览构建', result);
  expect(result.stdout).toContain('BUILD SUCCESSFUL');

  // 2. 在index.ets最后添加#符号 , 执行预览失败
  await commonFileOperation(path.resolve(entryRootPath, 'src/main/ets/pages/Index.ets'), async (buffer) => {
    const content = buffer.toString();
    return `${content}#`;
  });
  try {
    const result = await runHvigorAsync(project.projectRootPath(), commands);

    record.addStep('在index.ets最后添加#符号 , 执行预览失败', result);
    expect(result.stderr).toContain('Unexpected character \';\'');
  } catch (e: any) {
    if (e.constructor.name === 'JestAssertionError') {
      throw e;
    }
    record.addStep('在index.ets最后添加#符号 , 执行预览失败', {
      stdout: e.stdout,
      stderr: e.stderr
    });
    expect(e.stderr).toContain('BUILD FAILED');
  }

  // 3. 在index.ets最后删除#符号 , 执行预览成功
  await commonFileOperation(path.resolve(entryRootPath, 'src/main/ets/pages/Index.ets'), async (buffer) => {
    const content = buffer.toString();
    return content.replace('#', '');
  });
  const result2 = await runHvigorAsync(project.projectRootPath(), commands);
  record.addStep('在index.ets最后去除#符号 , 执行预览成功', result2);
  expect(result2.stdout).toContain('BUILD SUCCESSFUL');
};

TestCaseBuilder.builder()
  .caseName('DTS2023031104220')
  // eslint-disable-next-line max-len
  .description('【DevEco Studio】【SDV】【预览器】【修改引入】【HOS/OHOS】【API9】【ArkTS】【mac/win】在arkts工程中输入"#"符号触发热加载预览失败后，删除符号后触发热加载不生效。')
  .projectBuilderOption(projectBuilderOption)
  .taskConfig(TestTaskOptionBuilder.builder().caseLevel(CaseLevel.DTS).build())
  .testFun(testfun)
  .load();
